import requests
import logging
from tkinter import scrolledtext

find_todo_box_url = "http://136.64.71.234:30121/aiops/api/v1/flow/tj/constructionWorkTable/getGzConstructionInfo"
find_formIdAndPid_url = "http://136.64.71.234:30121/aiops/api/v1/form/getFlowForm"
find_broadband_info_url = "http://136.64.71.234:30121/aiops/api/v1/form/getFormData"
proxies = {
    "http": "http://136.64.71.234:30121",
    "https": "http://136.64.71.234:30121"
}

def getCookie():
    try:
        # 设置 Chrome 驱动路径
        chrome_driver_path = r"C:\Program Files\Google\Chrome\Application\chrome.exe"  # 替换为你的 ChromeDriver 路径
        options = Options()
        options.add_argument("--start-maximized")  # 启动时最大化窗口
        options.add_argument("--disable-extensions")
        options.add_argument("--headless")
        options.add_argument("--disable-popup-blocking")


        # 创建 WebDriver 实例
        service = Service(chrome_driver_path)
        driver = webdriver.Chrome(service=service, options=options)

        print("打开浏览器成功")
        # 打开登录页面
        login_url = "http://136.64.71.234:30121/aiops/loginm/sign"  # 替换为实际的登录 URL
        driver.get(login_url)
        print("条i转")

        print("请手动登录，然后按 Enter 继续...")
        input("按 Enter 键继续...")

        # 获取 Cookie
        cookies = driver.get_cookies()
        cookie_str = "; ".join([f"{cookie['name']}={cookie['value']}" for cookie in cookies])

        # 打印并插入 Cookie
        print("Cookie:", cookie_str)
        cookie_text.delete("1.0", tk.END)  # 清空之前的 Cookie
        cookie_text.insert(tk.END, cookie_str)  # 插入新的 Cookie

        # 关闭浏览器
        driver.quit()
    except requests.RequestException as e:
        logging.error(f"获取 Cookie 失败: {e}")
        showerror(title="获取Cookie", message="获取失败,请手动到浏览器复制Cookie")

def submit():
    access_codes = access_number_text.get("1.0", tk.END).strip().split('\n')
    cookie = cookie_text.get("1.0", tk.END).strip()
    headers = {"Content-Type": "application/json;charset=UTF-8", "Cookie": cookie}

    log_text.config(state="normal")
    log_text.delete("1.0", tk.END)  # 清空日志区域
    result_text.delete("1.0", tk.END)  # 清空结果区域
    log_text.config(state="disabled")

    total_codes = len(access_codes)
    for idx, access_code in enumerate(access_codes, start=1):
        result_param_1 = step_one_get_base_data(access_code.strip(), headers)
        if result_param_1:
            step_two_result = getFormIdAndPid(result_param_1, headers)
            if step_two_result:
                finalResult = getBroadbandData(step_two_result, headers)
                if finalResult:
                    log_text.config(state="normal")
                    log_output1 = f"{idx}. 查询接入号: {access_code} 成功\n"
                    log_text.insert(tk.END, log_output1)
                    log_text.config(state="disabled")

                    result_output = f"{idx}. 地址: {finalResult.get('address', '无')} --- 账号列表: {finalResult.get('accounts', '无')} \n"
                    result_text.insert(tk.END, result_output)
                else:
                    log_text.config(state="normal")
                    output1 = f"{idx}. 查询接入号: {access_code} 失败: 3\n"
                    log_text.insert(tk.END, output1)
                    log_text.config(state="disabled")
                    result_text.insert(tk.END, output1)
            else:
                log_text.config(state="normal")
                output1 = f"{idx}. 查询接入号: {access_code} 失败: 2\n"
                log_text.insert(tk.END, output1)
                log_text.config(state="disabled")
                result_text.insert(tk.END, output1)
        else:
            log_text.config(state="normal")
            output1 = f"{idx}. 查询接入号: {access_code} 失败: 1\n"
            log_text.insert(tk.END, output1)
            log_text.config(state="disabled")
            result_text.insert(tk.END, output1)

        # 更新进度条
        progress_label.config(text=f"进度: {idx}/{total_codes}")
        result_text.update()
        log_text.update()

def step_one_get_base_data(access_code, headers):
    payload = {
        "accessNo": access_code,
        "type": "B",
        "page": 0,
        "pageSize": 12
    }
    try:
        response = requests.post(find_todo_box_url, headers=headers, json=payload, proxies=proxies, timeout=(5, 30))
        if response.status_code == 200:
            re = response.json()
            if re and "content" in re:
                for key in re.get("content", []):
                    result_param = {
                        "flow_id": key.get("flow_id"),
                        "access_no": key.get("access_no"),
                        "address": key.get("address"),
                        "url": key.get("url")
                    }
                    return result_param
        else:
            logging.error(f"获取 接入号: {access_code} 的基础数据失败, 状态码: {response.status_code}, 响应内容: {response.text}")
            return None
    except requests.RequestException as e:
        logging.error(f"请求失败: {e}")
        return None

def getFormIdAndPid(result_param, headers):
    params = {'flowId': result_param.get("flow_id")}
    try:
        step_two_result = requests.get(find_formIdAndPid_url, headers=headers, params=params, proxies=proxies, timeout=(5, 30))
        if step_two_result.status_code == 200:
            step_two_result = step_two_result.json()
            if step_two_result:
                table_root = step_two_result["table"]
                for table in table_root:
                    for t_tmp in table.get("field", {}):
                        if t_tmp.get("fieldName") == "REQUEST_ID":
                            result_param["pId"] = t_tmp.get("value")
                        if t_tmp.get("fieldName") == "product_list_tab":
                            a = t_tmp.get("value")
                            result_param["formId"] = a.get("formId")
            return result_param
        else:
            logging.error(f"获取 接入号: {result_param.get('access_no')} 的 Form-Pid 数据失败, 状态码: {step_two_result.status_code}, 响应内容: {step_two_result.text}")
            return None
    except requests.RequestException as e:
        logging.error(f"请求失败: {e}")
        return None

def getBroadbandData(step_two_result, headers):
    params = {'formId': step_two_result.get("formId"), "pId": step_two_result.get("pId"), "pageNum": 0, "pageSize": 5}
    try:
        step_three_result = requests.get(find_broadband_info_url, headers=headers, params=params, proxies=proxies, timeout=(5, 30))
        if step_three_result.status_code == 200:
            step_three_result = step_three_result.json()
            if len(step_three_result) > 0:
                access_number = []
                data = step_three_result['data']
                for result_temp in data:
                    access_number.append(result_temp["accessNo"])
                access_number_unique = list(set(access_number))
                step_two_result["accounts"] = access_number_unique
                return step_two_result
        else:
            logging.error(f"获取 接入号: {step_two_result.get('access_no')} 的宽带详情数据失败")
            return None
    except requests.RequestException as e:
        logging.error(f"请求失败: {e}")
        return None
